package com.sskj.gocoin.v.activity;

import android.support.design.widget.BottomSheetDialog;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.jkb.vcedittext.VerificationCodeEditText;
import com.sskj.gocoin.MyAppLication;
import com.sskj.gocoin.R;
import com.sskj.gocoin.R2;
import com.sskj.gocoin.common.App;
import com.sskj.gocoin.common.widget.ToolBarLayout;
import com.sskj.gocoin.component.DaggerUserDataComponent;
import com.sskj.gocoin.m.bean.GoogleCode;
import com.sskj.gocoin.p.activity.VerifyGooglePresenter;
import com.sskj.gocoin.utils.CheckUtil;
import com.sskj.gocoin.utils.ClickUtil;
import com.sskj.gocoin.utils.CopyUtil;
import com.sskj.gocoin.utils.ToastUtil;
import com.sskj.gocoin.v.base.BaseActivity;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.DisposableSubscriber;

/**
 * ProjectName：ioaex
 * DESC: (谷歌认证)
 * Created by 李岩 on 2018/8/30 0030
 * updateName:(修改人名称)
 * updateTime:(修改时间)
 * updateDesc:(修改内容)
 */
public class VerifyGoogleActivity extends BaseActivity<VerifyGooglePresenter> {
    @BindView(R2.id.toolBar)
    ToolBarLayout mToolBar;
    @BindView(R2.id.iv_qr_code)
    ImageView mIvQrCode;
    @BindView(R2.id.tv_code)
    TextView mTvCode;
    @BindView(R2.id.tv_code_copy)
    TextView mTvCodeCopy;
    @BindView(R2.id.google_a_layout)
    LinearLayout mGoogleALayout;
    @BindView(R2.id.etVerificationCode)
    VerificationCodeEditText mEtVerificationCode;
    @BindView(R2.id.google_b_layout)
    LinearLayout mGoogleBLayout;
    @BindView(R2.id.btn_next)
    Button mBtnNext;
    private BottomSheetDialog sellDialog;
    private TextView mTvCount;
    private String mGoogleAuthCode;
    /**
     * 判断用户是否验证成功
     */
    private boolean isSuccess;
    @Inject
    UserViewModel userViewModel;
    private UserData userData;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_verify_google;
    }

    @Override
    public VerifyGooglePresenter getPresenter() {
        return new VerifyGooglePresenter();
    }

    @Override
    protected void initView() {
        super.initView();
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
        });

        mPresenter.requestData();
        mToolBar.setLeftButtonOnClickLinster(v -> {
            onBackClick();
        });

        ClickUtil.click(mTvCodeCopy, () -> {
            String trim = mTvCode.getText().toString().trim();
            CopyUtil.copy(trim);
        });
        ClickUtil.click(mBtnNext, () -> {
            showSmsVerifyDialog();
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackClick();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 退出
     */
    private void onBackClick() {
        if (mGoogleALayout.getVisibility() == View.VISIBLE) {
            finish();
        } else if (mGoogleBLayout.getVisibility() == View.VISIBLE) {
            if (isSuccess) {
                finish();
            } else {
                mGoogleALayout.setVisibility(View.VISIBLE);
                mGoogleBLayout.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 显示手机验证码Dialog
     */
    private void showSmsVerifyDialog() {
        sellDialog = new BottomSheetDialog(this);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_check_sms, null);
        TextView btDeal = dialogView.findViewById(R.id.tv_cancel);
        TextView tvPhoneWithHide = dialogView.findViewById(R.id.tv_phone_with_hide);
        EditText etCode = dialogView.findViewById(R.id.et_code);
        EditText etGoogleCode = dialogView.findViewById(R.id.et_google_code);
        mTvCount = dialogView.findViewById(R.id.tv_count);
        Button btSubmit = dialogView.findViewById(R.id.bt_submit);
        String mobile = MyAppLication.getMobile();
        ClickUtil.click(btSubmit, () -> {
            String authCode = etCode.getText().toString();
            if (TextUtils.isEmpty(authCode)) {
                ToastUtil.getInstance(MyAppLication.getApplication()).showMessage(App.INSTANCE.getString(R.string.strVerifyGoogleActivity201));
                return;
            }
            if (TextUtils.isEmpty(etGoogleCode.getText())) {
                ToastUtil.getInstance(MyAppLication.getApplication()).showMessage(App.INSTANCE.getString(R.string.fabimineJavaVerifyGoogleActivity1));
                return;
            }
            mPresenter.submit(mobile, authCode, etGoogleCode.getText().toString());
        });
        ClickUtil.click(mTvCount, () -> {
            if (CheckUtil.isEmail(mobile)) {
                mPresenter.sendEmail();
            } else {
                mPresenter.requestAuthCode(mobile);
            }
        });
        ClickUtil.click(btDeal, () -> {
            sellDialog.dismiss();
        });
        sellDialog.setContentView(dialogView);
        sellDialog.show();
    }

    private DisposableSubscriber<Long> disposableSubscriber;

    public void startCount() {
        mTvCount.setEnabled(false);
        disposableSubscriber = new DisposableSubscriber<Long>() {
            @Override
            public void onNext(Long aLong) {
                int time = (int) (60 - aLong);
                if (mTvCount != null) {
                    mTvCount.setText(time + App.INSTANCE.getString(R.string.strVerifyGoogleActivity202));
                    mTvCount.setTextColor(getResources().getColor(R.color.colorHintTextShow));
                }
            }

            @Override
            public void onError(Throwable t) {
                System.out.println(t.toString());
            }

            @Override
            public void onComplete() {
                if (mTvCount != null) {
                    mTvCount.setText(App.INSTANCE.getString(R.string.strVerifyGoogleActivity203));
                    mTvCount.setEnabled(true);
                }
                if (!disposableSubscriber.isDisposed()) {
                    disposableSubscriber.dispose();
                    disposableSubscriber = null;
                }

            }
        };
        Flowable.interval(0, 1, TimeUnit.SECONDS, Schedulers.newThread())
                .take(60)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(disposableSubscriber);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (disposableSubscriber != null && !disposableSubscriber.isDisposed()) {
            disposableSubscriber.dispose();
            disposableSubscriber = null;
        }
    }

    public void onGoogleCodeSuccess(GoogleCode obj) {
        mTvCode.setText(obj.getCommand());
        RequestOptions requestOptions = new RequestOptions();
        requestOptions.skipMemoryCache(true);
        requestOptions.diskCacheStrategy(DiskCacheStrategy.NONE);
        Glide.with(mActivity).load(obj.getLocal_url()).apply(requestOptions).into(mIvQrCode);
//        QRCodeUtil.createImage(obj.getLocal_url(), (int) RudenessScreenHelper.pt2px(this, 230), new QRCodeUtil.OnEncodeQRCodeCallback() {
//            @Override
//            public void onAnalyzeSuccess(Bitmap bitmap) {
////                mbitmap = bitmap;
//                mIvQrCode.setImageBitmap(bitmap);
//            }
//
//            @Override
//            public void onAnalyzeFailed() {
//
//            }
//        });
    }

    public void onBindSuccess() {
        finish();
        isSuccess = true;
    }

    public void onAuthCodeSuccess() {
        startCount();
    }
}
